import React, { useEffect, useState, useCallback, useMemo } from 'react';
import { Table, Form, Input, Button, Modal } from 'antd';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import type { FilterValue, SorterResult } from 'antd/es/table/interface';
import { DataType, getDishAPI, getDishPage } from '@/service/dish';
import { ShoppingTwoTone } from '@ant-design/icons';

const queryPage: getDishPage = {
  name: '',
  classify: 0,
  current: 1,
  size: 10,
  restaurantId: 0,
  sortField: '',
  sortOrder: '',
};

interface TableParams {
  pagination?: TablePaginationConfig;
  sortField?: string;
  sortOrder?: string;
  filters?: Record<string, FilterValue>;
}

const { Search } = Input;

const App: React.FC = () => {
  //获取餐厅id
  const restaurantId = localStorage.getItem('restaurant');
  queryPage.restaurantId = Number(restaurantId);
  const [order, setOrder] = useState(
    JSON.parse(localStorage.getItem('restaurantId' + restaurantId) || '{}'),
  );
  const [data, setData] = useState<DataType[]>();
  const [loading, setLoading] = useState(false);
  const [tableParams, setTableParams] = useState<TableParams>({
    pagination: {
      current: 1,
      pageSize: 10,
    },
  });

  function updateOrder(id: number, change: number, number?: number) {
    // 使用restaurantId作为键来获取order
    let order = JSON.parse(
      localStorage.getItem('restaurantId' + restaurantId) || '{}',
    );
    debugger;
    let count = (order[id] || 0) + change;
    if (number != undefined) {
      if (count > number) {
        Modal.info({
          title: '提示',
          content: '库存不足',
        });
        return;
      }
    }
    order[id] = count;
    debugger;
    if (order[id] <= 0) {
      delete order[id];
    }

    // 使用restaurantId作为键来存储order
    localStorage.setItem('restaurantId' + restaurantId, JSON.stringify(order));
    debugger;
    setOrder(order);
    // localStorage.removeItem('restaurantId' + restaurantId);
    return order;
  }

  useEffect(() => {
    localStorage.setItem('restaurantId' + restaurantId, JSON.stringify(order));
  }, [order]);

  const columns: ColumnsType<DataType> = useMemo(
    () => [
      {
        title: '图片',
        dataIndex: 'image',
        render: (image) => (
          <img
            src={`http://localhost:10001/ftp/download?fileName=${image}&path=dish`}
            alt=""
            width="100"
            height="100"
          />
        ),
        width: '10%',
      },
      {
        title: '菜名',
        dataIndex: 'name',
        sorter: true,
        render: (name) => `${name}`,
        width: '15%',
      },
      {
        title: '分类',
        dataIndex: 'classify',
        filters: [
          { text: '未分类', value: '1' },
          { text: '热菜', value: '2' },
          { text: '凉菜', value: '3' },
          { text: '主食', value: '4' },
          { text: '汤类', value: '5' },
          { text: '饮品', value: '6' },
          { text: '甜品', value: '7' },
          { text: '其他', value: '8' },
        ],
        render: (classify) => `${classify}`,
        width: '10%',
      },
      {
        title: '库存',
        dataIndex: 'number',
        sorter: true,
        render: (number) => `${number} 份`,
        width: '10%',
      },
      {
        title: '评分',
        dataIndex: 'score',
        sorter: true,
        render: (score) => `${score} 分`,
        width: '10%',
      },
      {
        title: '销量',
        dataIndex: 'sales',
        sorter: true,
        render: (sales) => `${sales} 分`,
        width: '10%',
      },
      {
        title: '价格',
        dataIndex: 'price',
        sorter: true,
        render: (price) => `￥${price}元`,
        width: '10%',
      },
      {
        title: '下单',
        dataIndex: 'id',
        render: (id, record) => {
          // 从状态中获取当前商品的数量
          let order = JSON.parse(
            localStorage.getItem('restaurantId' + restaurantId) || '{}',
          );
          let count = order[record.id] || 0;

          return (
            <>
              <Button onClick={() => updateOrder(record.id, -1)}>-1</Button>
              <span>{count}</span>
              <Button onClick={() => updateOrder(record.id, 1, record.number)}>
                +1
              </Button>
            </>
          );
        },
        width: '10%',
      },
    ],
    [order],
  );

  //发送查询请求
  const fetchData = useCallback(async () => {
    setLoading(true);
    setData([]);

    try {
      const res = await getDishAPI(queryPage);
      setData(res.records);
      setTableParams((prevParams) => ({
        ...prevParams,
        pagination: {
          current: res.current,
          pageSize: res.size,
          total: res.total,
          ...prevParams.pagination,
        },
      }));
    } finally {
      setLoading(false);
    }
  }, [tableParams]);

  //监听tableParams的变化
  useEffect(() => {
    fetchData();
  }, [JSON.stringify(tableParams)]);

  //监听queryPage的变化
  const handleTableChange = useCallback(
    (
      pagination: TablePaginationConfig = {},
      filters: Record<string, FilterValue> = {},
      sorter: SorterResult<DataType> = {},
    ) => {
      setTableParams({
        pagination,
        filters,
        ...sorter,
      });
      queryPage.classify = (filters && Number(filters.classify)) || 0;
      queryPage.current = (pagination && Number(pagination.current)) || 1;
      queryPage.size = (pagination && Number(pagination.pageSize)) || 10;
      //如果为undefined则转换为'' String类型
      queryPage.sortField = sorter && sorter.field ? String(sorter.field) : '';
      queryPage.sortOrder =
        sorter && sorter.order === 'descend'
          ? 'desc'
          : sorter && sorter.order === 'ascend'
          ? 'asc'
          : '';
    },
    [tableParams],
  );

  //搜索
  const onSearch = useCallback(
    (value: string) => {
      queryPage.name = value;
      handleTableChange();
    },
    [handleTableChange],
  );

  return (
    <div>
      <Form>
        <Search
          placeholder="菜品名称"
          allowClear
          enterButton="Search"
          size="small"
          onSearch={onSearch}
          maxLength={10}
        />
      </Form>
      <Table
        columns={columns}
        rowKey={(record) => record.id}
        dataSource={data}
        loading={loading}
        onChange={handleTableChange}
        pagination={tableParams.pagination}
        scroll={{ y: 530 }}
      />
    </div>
  );
};

export default App;
